using System;
using ECommerce.IntegrationSpecs.Properties;
using ECommerce.IntegrationSpecs.TestHelpers;
using ECommerce.Web;
using ECommerce.Web.NHibernate;
using ECommerce.Web.NHibernate.ConfigurationBuilders;
using ECommerce.Web.NHibernate.Sessions;
using Machine.Specifications;
using NHibernate;
using Selenium;
using NHibernateCfg = NHibernate.Cfg;

namespace ECommerce.IntegrationSpecs
{
    public abstract class WebContext
    {
        private static ISession session;

        protected static ISession Session
        {
            get { return session; }
        }

        private static ISelenium selenium;

        protected static ISelenium Browser
        {
            get { return selenium; }
        }
        
        Establish context = () =>
            {
                Bootstrapper.ConfigureServiceLocator();

                var configurationBuilder = new DefaultConfigurationBuilder();

                NHibernateCfg.Configuration configuration = configurationBuilder.Build(PersistenceOptions.Default());

                Bootstrapper.ConfigureSessionSource(configuration);

                session = SessionSource.Current.GetSession();

                selenium = new DefaultSelenium("localhost", 4444, "*firefox", Settings.Default.WebApplicationBaseUrl);

                selenium.Start();
            };

        Cleanup cleanup = () =>
            {
                SessionSource.Current.CloseSession();

                if (selenium != null)
                {
                    selenium.Stop();
                }
            };

        protected static View<T> ViewFor<T>()
        {
            return new View<T>(selenium);
        }

        protected static Form<T> FormFor<T>()
        {
            return new Form<T>(selenium);
        }

        protected static void NavigateTo(string view)
        {
            selenium.Click(String.Format("xpath=//a[@rel='{0}']", view));
        }

        protected static void ViewShouldBe(string view)
        {
            selenium.GetValue("id=view").ShouldEqual(view);
        }
    }
}